package cn.wolfcode.shop.cloud.web.controller;


import cn.wolfcode.shop.cloud.BusinessException;
import cn.wolfcode.shop.cloud.Result;
import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.domain.SeckillOrder;
import cn.wolfcode.shop.cloud.member.domain.User;
import cn.wolfcode.shop.cloud.member.util.ParamType;
import cn.wolfcode.shop.cloud.mq.MQConstans;
import cn.wolfcode.shop.cloud.mq.OrderMessage;
import cn.wolfcode.shop.cloud.msg.SeckillGoodsCodeMsg;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.service.ISeckillOrderService;
import cn.wolfcode.shop.cloud.service.RedisService;
import cn.wolfcode.shop.cloud.util.SeckillKeyPrefix;
import cn.wolfcode.shop.cloud.vo.SeckillGoodVO;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;


@RestController
public class SeckillOrderInfoController {
    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    public static final ConcurrentHashMap<Long,Boolean>  isOverSign = new ConcurrentHashMap<>();

    @RequestMapping("/order/find")
    public Result find(String orderNo,@ParamType User user){
        //如果没有登录
        if(user == null){
            return Result.error(SeckillGoodsCodeMsg.USER_NOT_LOGIN);
        }
        //如果订单编号没有查询到值  ,这个可能是伪造的订单编号
        OrderInfo orderInfo = orderInfoService.find(orderNo);
        if(orderInfo == null){
            return Result.error(SeckillGoodsCodeMsg.SECKILL_OPT);
        }
        //确保这个订单是 当前登录的用户
        if(!orderInfo.getUserId().equals(user.getId())){
            return Result.error(SeckillGoodsCodeMsg.SECKILL_OPT);
        }

        return Result.success(orderInfo);
    }



    @RequestMapping("/{path}/doSeckill")
    public Result doSeckill(@PathVariable String path, Long seckillId,@ParamType User user,String uuid){

        //1 用户是否登录,只有登录了才可以进行秒杀
        if(user == null){
            return Result.error(SeckillGoodsCodeMsg.SECKILL_OPT);
        }

        //判断路径是否合法,隐藏地址
        String p = redisService.get(SeckillKeyPrefix.SECKILL_PATH, uuid, String.class);
        if(path==null || p == null ||  !path.equals(p)){
            return Result.error(SeckillGoodsCodeMsg.SECKILL_OPT);
        }

        //根据本地标识去进行判断
        //目的:防止多余无效的请求访问redis造成网络开销
        Boolean flag = isOverSign.get(seckillId);
        if(flag!=null && flag){
            return Result.error(SeckillGoodsCodeMsg.SECKILL_OPT);
        }

        /*String p = redisService.get(SeckillKeyPrefix.SECKILL_PATH, uuid, String.class);
        if(path==null || p == null ||  !path.equals(p)){
            return Result.error(SeckillGoodsCodeMsg.SECKILL_OPT);
        }

        Integer code = (Integer) redisService.get(SeckillKeyPrefix.SECKILL_VERIFYCODE,uuid,Integer.class);
        if(verifyCode == null || code == null){
            return Result.error(SeckillGoodsCodeMsg.VERIFY_CODE_EMPTY);
        }

        if(!verifyCode.equals(code+"")){
            return Result.error(SeckillGoodsCodeMsg.SECKILL_VERIFY_CODE_ERROR);
        }

        //根据本地标识去进行判断
        Boolean flag = isOverSign.get(seckillId);
        if(flag!=null && flag){
            return Result.error(SeckillGoodsCodeMsg.SECKILL_OPT);
        }*/


        //2 根据秒杀商品id查询 数据,如果查询不到,非法操作
        //SeckillGoodVO seckillGoodVO = seckillService.find(seckillId);
        SeckillGoodVO seckillGoodVO = seckillGoodService.findByCache(seckillId);
        if(seckillGoodVO == null){
            return Result.error(SeckillGoodsCodeMsg.SECKILL_OPT);
        }
        //3  判断当前的秒杀的商品是否已经开始秒杀了,并且还要判断是否结束了
        // startDate  2020 4 - 24  12: 00  endDate 2020 4 - 24 13:00
        //  如果当前时间 小于开始时间 或是大于结束时间那么是违法操作
        Date now = new Date();
        if(now.getTime() < seckillGoodVO.getStartDate().getTime() || now.getTime()> seckillGoodVO.getEndDate().getTime() ){
            return Result.error(SeckillGoodsCodeMsg.SECKILL_OPT);
        }
        //4 同一个用户不能够重复的秒杀商品
       /* SeckillOrder seckillOrder = seckillOrderService.queryByUserIdAndSeckillId(user.getId(),seckillId);
        if(seckillOrder != null){
            throw new BusinessException(SeckillGoodsCodeMsg.SECKILL_REPEAT);
        }*/
        if(redisService.exists(SeckillKeyPrefix.SECKILL_ORDER,user.getId()+":"+seckillId)){
            return Result.error(SeckillGoodsCodeMsg.SECKILL_REPEAT);
        }
        //5 判断库存是否足够
        /*if (seckillGoodVO.getStockCount() <= 0){
            return Result.error(SeckillGoodsCodeMsg.SECKILL_OVER);
        }*/

        long count = redisService.decr(SeckillKeyPrefix.SECKILL_STOCK, seckillId + "");
        if(count < 0){
            isOverSign.put(seckillId,true);
            return Result.error(SeckillGoodsCodeMsg.SECKILL_OVER);

        }

        //6 秒杀操作
        // 减少库存,创建订单信息存入数据库,往t_seckill_order存储一条数据

       /* String orderNo = orderInfoService.seckill(user.getId(),seckillId);
        return Result.success(orderNo);
        */

       /* if (seckillGoodVO.getStockCount() <= 0){
            return Result.error(SeckillGoodsCodeMsg.SECKILL_OVER);
        }

        long count = redisService.decr(SeckillKeyPrefix.SECKILL_STOCK, seckillId + "");
        if(count<0){
            isOverSign.put(seckillId,true);
            return Result.error(SeckillGoodsCodeMsg.SECKILL_OVER);

        }

        */

        //发送消息
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setSeckillId(seckillId);
        orderMessage.setUserId(user.getId());
        orderMessage.setUuid(uuid);
        //同步发送信息
        rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_DEST,orderMessage);
        //String orderNo = orderInfoService.seckill(user.getId(),seckillId);
        return Result.success("正在抢购中.. 请等待结果");
    }
}
